package com.tydic.test_ws.controller;

import com.tydic.webservice.Customer;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test_ws2")
public class Test2WsController {

    private Client createWsClient(){
        //创建动态客户端
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        Client client = factory.createClient("http://localhost:8082/srti/api?wsdl");
        // 需要密码的情况需要加上用户名和密码
        //client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,PASS_WORD));
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        httpClientPolicy.setConnectionTimeout(2000);  //连接超时
        httpClientPolicy.setAllowChunking(false);    //取消块编码
        httpClientPolicy.setReceiveTimeout(120000);     //响应超时
        conduit.setClient(httpClientPolicy);
        //client.getOutInterceptors().addAll(interceptors);//设置拦截器

        return client;
    }

    @GetMapping("/hello2/{name}")
    public String hello(@PathVariable("name")String name){
        Client client = createWsClient();
        Object[] objects = new Object[0];
        try{
            // invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke("testString", name);
            System.out.println("返回数据:" + objects[0]);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "" + objects[0];
    }

    @GetMapping("/testMap2")
    public Object testMap(){
        Client client = createWsClient();
        Object[] objects = new Object[0];
        try {
            Customer customer = new Customer();
            customer.setSuccess(true);
            customer.setName("customer");
            customer.setMessage("webservice客户端调用服务端方法");
            objects = client.invoke("testMap", customer);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return objects;
    }

}
